import React from 'react'
import ReactDOM from 'react-dom'
import * as PropertyAction  from '../../actions/PropertyAction';
import { connect }  from 'react-redux';

import _ from "lodash"

class BackgroundPropertySettingTools extends React.Component {
  constructor(props){
    super(props)
  }

  componentDidMount(){
    this.props.dispatch(
      PropertyAction.loadPropertyDataAsync({
      })
    )
    // console.log(this.props.data);
  }

  onDataSearch(event) {
    var input = $(event.target);
    var value = $(input).val();
    this.props.onDataSearch(value)
  }

  onPropertyFilterClick(data) {
    var name = data.name;
    var hasOne = _.find(this.props.data, function(property) {
      return property.name == name;
    })

    if (!hasOne) {
      name = "";
    }
    this.props.onPropertyFilterClick(name)
    $(ReactDOM.findDOMNode(this.refs.propertyDrop)).html(name.length>0?name: "小区物业" )
  }

  renderList() {
    var self = this;
    var content = [];
    // console.log(this.props.data);
    if (this.props.data && this.props.data.length > 0) {
      this.props.data.forEach(function(data, index) {
        // console.log(data);
        content.push((
            <li><a href="#" onClick={(event)=>self.onPropertyFilterClick(data)}>{data.name}</a></li>
        ))
      })
    }

    return content
  }

  render(){
    var self = this
    return (
      <div className="background-role-tools row">
        <div className="btn-group col-xs-2 col-sm-2 col-lg-2">
          <button  type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <span ref="propertyDrop">小区物业</span>
            <span className="caret"></span>
          </button>
          <ul className="dropdown-menu">
            <li><a href="#" onClick={(event)=>self.onPropertyFilterClick({})}>小区物业</a></li>
            <li role="separator" className="divider"></li>
            {this.renderList()}
          </ul>
        </div>
        <div className="col-xs-2 col-sm-2 col-lg-2 col-xs-offset-8 col-sm-offset-8 col-lg-offset-8  create-button">
          <button type="button" className="btn-create"
                  onClick={(event)=>this.props.onCreateClick()}>添加</button>
        </div>

      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    data: state.properties
  }
}

export default connect(mapStateToProps)(BackgroundPropertySettingTools);
